# coding=utf-8
from flask import *
from flask import Flask, render_template, Blueprint, request, send_file,redirect,flash, url_for, session
from flask_docs import ApiDoc
import requests
from xingzuo import get_xingzuo
from linksql import *
from send_email import *
from get_meituan_meishi import *
# 将繁体换为简体
from baidu_tra import *
# 唐诗宋诗数据库
from collections import OrderedDict
from poem_data import *
import json,os
from Speech_Synthesis import *
from send_emails import *
import datetime, random
from face import *
import time
import cv2,os,shutil
from DMS_linksql import *
from datetime import timedelta
from flask_cors import *
global upload_path
app = Flask(__name__, static_folder='static')
app.config.from_object(__name__)
app.secret_key = 'dasd5sdfasgsd7fsduy8vbcv5d='
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=1)
CORS(app, resources=r'/*')
# # 接口文档样式
# # 需要显示文档的 Api
# from flask_docs import ApiDoc
app.config['API_DOC_MEMBER'] = ['poem']
# 需要排除的 RESTful Api 文档
# app.config['RESTFUL_API_DOC_EXCLUDE'] = []
poem = Blueprint('poem', __name__)
ApiDoc(app)
def write_json(test_dict):
    json_str = json.dumps(test_dict, indent=4,ensure_ascii=False)
    with open('author_data.json', 'w',encoding='utf-8') as json_file:
        json_file.write(json_str)

def get_user_data(data):
    data_temp = {}
    data_temp['nickName'] = data[1]
    data_temp['openid'] = data[0]
    if data[3]=='1':
        data_temp['gender'] = '男'
    elif data[3]=='2':
        data_temp['gender'] = '女'
    else:
        data_temp['gender'] = '未知'
    data_temp['sign'] = data[4]
    data_temp['Date'] = '2000.01.04'
    data_temp['Time'] = '00:08 AM'
    return data_temp

def get_author_data(data):
    data_temp = {}
    data_temp['nickName'] = data['poemName']
    data_temp['openid'] = data['author']
    data_temp['gender'] = '未知'
    data_temp['sign'] = data['poem']
    data_temp['Date'] = '2000.01.04'
    data_temp['Time'] = '00:08 AM'
    return data_temp


def paging(page, limit, dictArray):
    start = (page - 1) * limit
    end = page * limit if len(dictArray) > page * limit else len(dictArray)
    ret = [dictArray[i] for i in range(start, end)]
    all_page = int(len(dictArray)/limit)+1
    return ret, all_page
    
# 首页
@app.route('/')
def index():
    return render_template('index.html')
#@app.route('/<path>')
#def today(path):
#    base_dir = os.path.dirname(__file__)
#    resp = make_response(open(os.path.join(base_dir, path)).read())
#    resp.headers["Content-type"]="text/plan;charset=UTF-8"
#    return resp

#------------------------------------bishe-----------------------------------------#
##################################################################################################################
@app.route('/root_index', methods=['GET', 'POST'])
def root_index():
    try:
        if 'username' in session and session['username'] == 'cxk':
            return redirect(url_for('data_index'))
        return render_template('login.html')
    except Exception as e:
        write_error(e)

@app.route("/login",methods=["GET","POST"])
def login():
    try:
        rootname = request.form.get('username')
        password = request.form.get('password')
        session['username'] = rootname
        if 'cxk' == rootname and 'cxk19971123....' == password:
            return redirect(url_for('data_index'))
        else:
            return redirect(url_for('root_index'))
    except Exception as e:
        write_error(e)

@app.route('/logout', methods=['GET'])
def logout():
    session.clear()
    return redirect(url_for('root_index'))
    
@app.route('/data_index')
def data_index():
    try:
        if 'username' in session and session['username'] == 'cxk':
            datas = []
            for i in use_select_all():
                data = get_user_data(i)
                datas.append(data)
            is_user = 0
            limit = 20
            page = 1
            datas, lenArray = paging(page, limit, datas)
            lenArray = [int(i) for i in range(1, lenArray)]
            return render_template('data_index.html', datas=datas, is_user=is_user, lenArray=lenArray[0:4], page=int(page))
        else:
            return redirect(url_for('root_index'))
    except Exception as e:
        write_error(e)
        return response_return('404', 'Request parameter error', None)

def get_author(chiose):
    if chiose=='tang':
        c = tang_poem_selectParagraphss('')
    if chiose=='ci':
        c = ci_poem_selectParagraphss('')
    if chiose=='song':
        c = song_poem_selectParagraphss('')
    poemList=[]
    for i in c:
        try:
            poemDict = {}
            poemDict['poemName'] = i[1]
            poemDict['author'] = i[2]
            poemDict['poem'] = i[3]
            poemList.append(poemDict)
        except:
            poemDict['poem'] = i[3]
    print(len(poemList))
    author_dict = {}
    for i in poemList:
        if i['author'] not in author_dict.keys():
            author_dict[i['author']] = 1
        else:
            author_dict[i['author']] += 1
    author_dict = sorted(author_dict.items(),
                            key=lambda x: x[1], reverse=True)
    author = []
    number = []
    for i in range(len(author_dict)):
        if author_dict[i][0]!='无名氏':
            author.append(author_dict[i][0])
            number.append(author_dict[i][1])
    return author[0:11],number[0:11]


@app.route('/show_index')
def show_index():
    try:
        if 'username' in session and session['username'] == 'cxk':
            data = seach('')
            # print(data)
            author_dict = {}
            for i in data:
                if i['author'] not in author_dict.keys():
                    author_dict[i['author']] = 1
                else:
                    author_dict[i['author']] += 1
            author_dict = sorted(author_dict.items(),
                                 key=lambda x: x[1], reverse=False)
            author = []
            number = []
            for i in range(len(author_dict)):
                author.append(author_dict[i][0])
                number.append(author_dict[i][1])
            pieData=[]
            pieData_2=[]
            pieData_3=[]
            with open("all_poem_number.txt", "r",encoding='utf-8') as f:
                for line in f.readlines():
                    line = line.strip('\n')  #去掉列表中每一个元素的换行符
                    if len(line.split(':')[0])>2:
                        a={}
                        a['value']=int(line.split(':')[1])
                        a['name']=line.split(':')[0]
                        pieData_3.append(a)
                    elif len(line.split(':')[0])>1:
                        a={}
                        a['value']=int(line.split(':')[1])
                        a['name']=line.split(':')[0]
                        pieData_2.append(a)
                    else:
                        a={}
                        a['value']=int(line.split(':')[1])
                        a['name']=line.split(':')[0]
                        pieData.append(a)
            pieData=sorted(pieData,key=lambda keys:keys['value'],reverse=True)[0:4]
            pieData_2=sorted(pieData_2,key=lambda keys:keys['value'],reverse=True)[0:4]
            pieData_3=sorted(pieData_3,key=lambda keys:keys['value'],reverse=True)[0:2]
            pieData=pieData+pieData_2+pieData_3
            a,b=get_author('ci')
            c,d=get_author('tang')
            e,f=get_author('song')
            return render_template('show_index.html', author=json.dumps(author[::-1][0:15][::-1]),pieData=json.dumps(pieData[0:10]),number=json.dumps(number[::-1][0:15][::-1]), a=json.dumps(a),b=json.dumps(b),c=json.dumps(c),d=json.dumps(d),e=json.dumps(e),f=json.dumps(f),all_author=len(author))
        else:
            return redirect(url_for('root_index'))    
    except Exception as e:
        write_error(e)
        return response_return('404', 'Request parameter error', None)
        
@app.route('/page', methods=["POST", "GET"])
def page():
    page = int(request.form['page'])
    if page <= 1:
        page = 1
    print(page)
    datas = []
    for i in use_select_all():
        data = get_user_data(i)
        datas.append(data)
    is_user = 0
    limit = 20
    datas, lenArray = paging(page, limit, datas)
    lenArrays = [int(i) for i in range(page, lenArray)]
    if(len(lenArrays) > 4):
        lenArrays = lenArrays[0:4]
    else:
        lenArrays = [int(i) for i in range(1, lenArray)][-4:]
    return render_template('data_index.html', datas=datas, is_user=is_user, lenArray=lenArrays, page=int(page))


# 首页
@app.route('/data_insert', methods=["POST", "GET"])
def data_insert():
    try:
        data_temp = {}
        data_temp['Name'] = request.form['name']
        data_temp['Phone_Number'] = request.form['phone_number']
        data_temp['Car_number'] = request.form['car_number']
        data_temp['Where'] = request.form['Whereis']
        data_temp['Date'] = request.form['Date']
        data_temp['Time'] = request.form['Time']
        info_user_InsertData(data_temp['Name'], data_temp['Car_number'],
                             data_temp['Phone_Number'], data_temp['Where'], data_temp['Date'], data_temp['Time'])
        return json.dumps({'msg': 200, 'info': {'success': '数据上传成功！'}}, ensure_ascii=False)
    except:
        return json.dumps({'msg': 400, 'info': {'error': '请检查参数是否正确！'}}, ensure_ascii=False)

@app.route('/users')
def users():
    try:
        author_dict = {}
        if not os.path.exists("author_data.json"):
            data = seach('')
            for i in data:
                if i['author'] not in author_dict.keys():
                    author_dict[i['author']] = 1
                else:
                    author_dict[i['author']] += 1
            write_json(author_dict)
        else:
            with open("author_data.json", "r+",encoding='utf-8')as f:
                author_dict=json.load(f)
        author_dict = sorted(author_dict.items(),
                             key=lambda x: x[1], reverse=True)
        users=[]
        #len(author_dict)
        for i in range(len(author_dict)):
            user = {}
            user['author'] = author_dict[i][0]
            user['gender'] = 'Girl'
            user['poem_number'] = author_dict[i][1]
            users.append(user)
        limit = 20
        users, lenArray = paging(1, limit, users)
        is_user = 1
        return render_template('data_index.html',users=users, is_user=is_user, search='', page=1,data_page=1,len=lenArray)
    except Exception as e:
        write_error(e)
        return response_return('404', 'Request parameter error', None)

@app.route('/get_one_user', methods=["POST", "GET"])
def get_one_user():
    author = request.form['author']
    search = request.form['search']
    page = int(request.form['page'])
    data_page=1
    if search != '':
        datas = seach(author)
        data=[]
        for i in datas:
            temp_data = get_author_data(i)
            if temp_data['openid']==author:
                data.append(temp_data)
            else:
                pass
        author_dict={}
        with open("author_data.json", "r+",encoding='utf-8')as f:
            author_dict=json.load(f)
        author_dict = sorted(author_dict.items(),
                            key=lambda x: x[1], reverse=True)
        users=[]
        flag=0
        for i in range(len(author_dict)):
            user = {}
            if author==author_dict[i][0]:
                flag=i
            user['author'] = author_dict[i][0]
            user['gender'] = 'Girl'
            user['poem_number'] = author_dict[i][1]
            users.append(user)
        userss = []
        for i in users:
            values = []
            for value in i.values():
                values.append(value)
            datass = [i for i, x in enumerate(values) if str(x).find(search) != -1]
            if datass != []:
                userss.append(i)
        users = userss
        user = {}
        for i in users:
            if i['author'] == author:
                user = i
                author = author
        limit = 20
        lenArray= int(len(users)/limit)+1
        users, userlenArray = paging(1, limit, users)
        datas, datalenArray = paging(1, limit, data)
        lenArrays = [int(i) for i in range(1, datalenArray)]
        if(len(lenArrays) > 4):
            lenArrays = lenArrays[0:4]
        else:
            lenArrays = [int(i) for i in range(1, datalenArray)][-4:]
    else:
        datas = seach(author)
        data=[]
        for i in datas:
            temp_data = get_author_data(i)
            if temp_data['openid']==author:
                data.append(temp_data)
            else:
                pass
        users=[]
        author_dict={}
        with open("author_data.json", "r+",encoding='utf-8')as f:
            author_dict=json.load(f)
        author_dict = sorted(author_dict.items(),
                            key=lambda x: x[1], reverse=True)
        users=[]
        flag=0
        for i in range(len(author_dict)):
            user = {}
            if author==author_dict[i][0]:
                flag=i
            user['author'] = author_dict[i][0]
            user['gender'] = 'Girl'
            user['poem_number'] = author_dict[i][1]
            users.append(user)
        limit = 20
        user = {}
        lenArray= int(len(users)/limit)+1
        for i in users:
            if i['author'] == author:
                user = i
                author = author
        limit = 20
        users, userlenArray = paging(1, limit, users[flag:])
        datas, datalenArray = paging(1, limit, data)
        lenArrays = [int(i) for i in range(1, datalenArray)]
        if(len(lenArrays) > 4):
            lenArrays = lenArrays[0:4]
        else:
            lenArrays = [int(i) for i in range(1, datalenArray)][-4:]
    is_user = 2
    return render_template('data_index.html', datas=datas, users=users, user=user, is_user=is_user, author=author, search=search, lenArray=lenArrays, len=lenArray,page=page,data_page=data_page)

@app.route('/page_user', methods=["POST", "GET"])
def page_user():
    page = int(request.form['page'])
    data_page = int(request.form['data_page'])
    if page <= 1:
        page = 1
    author_dict={}
    with open("author_data.json", "r+",encoding='utf-8')as f:
        author_dict=json.load(f)
    author_dict = sorted(author_dict.items(),
                        key=lambda x: x[1], reverse=True)
    users=[]
    for i in range(len(author_dict)):
        user = {}
        user['author'] = author_dict[i][0]
        user['gender'] = 'Girl'
        user['poem_number'] = author_dict[i][1]
        users.append(user)
    is_user = 1
    limit = 20
    users, lenArray = paging(page, limit, users)
    if page >= lenArray:
        page = lenArray
    return render_template('data_index.html', is_user=is_user, users=users,page=int(page),data_page=data_page,len=lenArray)


@app.route('/page_poem', methods=["POST", "GET"])
def page_poem():
    author = request.form['author']
    page = int(request.form['page'])
    data_page= int(request.form['data_page'])
    if data_page <= 1:
        data_page = 1
    datas = seach(author)
    data=[]
    for i in datas:
        temp_data = get_author_data(i)
        if temp_data['openid']==author:
            data.append(temp_data)
        else:
            pass
    author_dict={}
    with open("author_data.json", "r+",encoding='utf-8')as f:
        author_dict=json.load(f)
    author_dict = sorted(author_dict.items(),
                        key=lambda x: x[1], reverse=True)
    users=[]
    flag=0
    for i in range(len(author_dict)):
        user = {}
        if author==author_dict[i][0]:
            flag=i
        user['author'] = author_dict[i][0]
        user['gender'] = 'Girl'
        user['poem_number'] = author_dict[i][1]
        users.append(user)
  
    user = {}
    for i in users:
        if i['author'] == author:
            user = i
            author = author
    is_user = 2
    limit = 20
    lenArray= int(len(users)/limit)+1
    users, userlenArray = paging(1, limit, users[flag:])
    datas, datalenArray = paging(data_page, limit, data)
    lenArrays = [int(i) for i in range(page, datalenArray)]
    if(len(lenArrays) > 4):
        lenArrays = lenArrays[0:4]
    else:
        lenArrays = [int(i) for i in range(1, datalenArray)][-4:]
    if data_page >= datalenArray:
        data_page = datalenArray
    return render_template('data_index.html', datas=datas, is_user=is_user, user=user, users=users, lenArray=lenArrays, len=lenArray,page=int(page),data_page=int(data_page), author=author)

@app.route('/search_user', methods=["POST", "GET"])
def search_user():
    search = request.form['search']
    if  search == '':
        return redirect("/users")
    users=[]
    author_dict={}
    with open("author_data.json", "r+",encoding='utf-8')as f:
        author_dict=json.load(f)
    author_dict = sorted(author_dict.items(),
                        key=lambda x: x[1], reverse=True)
    users=[]
    for i in range(len(author_dict)):
        user = {}
        user['author'] = author_dict[i][0]
        user['gender'] = 'Girl'
        user['poem_number'] = author_dict[i][1]
        users.append(user)
    userss = []
    for i in users:
        values = []
        for value in i.values():
            values.append(value)
        datass = [i for i, x in enumerate(values) if str(x).find(search) != -1]
        if datass != []:
            userss.append(i)
    users = userss
    is_user = 1
    return render_template('data_index.html', users=userss, is_user=is_user, search=search,len=1,page=1,data_page=1)

#######################################################################################################################



#------------------------------------bishe-----------------------------------------#

#------------------------------------远程文件-----------------------------------------#

def GetNameByEveryDir(file_dir):  
    # Input   Root Dir and get all img in per Dir.
    # Out     Every img with its filename and its dir and its path  
    FileNameWithPath = [] 
    FileName         = []
    FileDir          = []
    for root, dirs, files in os.walk(file_dir):  
        for file in files:  
            FileNameWithPath.append(os.path.join(root, file))  # 保存图片路径
            FileName.append(file)                              # 保存图片名称
            FileDir.append(root[len(file_dir):])               # 保存图片所在文件夹
    return FileName,FileNameWithPath,FileDir
    
@app.route('/get_file', methods=['GET', 'POST'])
def get_file():
    # # 获取所有的本机IPv4地址列表
    # import psutil
    # from socket import AddressFamily
    # local_address = []
    # for name , info in psutil.net_if_addrs().items():
    #     for addr in info:
    #         ## 只放入IPv4的地址
    #         if AddressFamily.AF_INET == addr.family :
    #             # if '192' not in addr.address:
    #             local_address.append("http://"+addr.address+":5000")
    # print(local_addrs[0])
    filepath = os.path.join(os.path.dirname(os.path.abspath('__file__')),'phone_win_file')
    if not os.path.exists(filepath):
        os.makedirs(filepath)
    FileName,FileNameWithPath,FileDir = GetNameByEveryDir(filepath)
    page=1
    limit=10            
    start = (page - 1) * limit                
    end = page * limit if len(FileName) > page * limit else len(FileName)                              
    ret = [FileName[i] for i in range(start, end)]
    all_page=int(len(FileName)/limit)+1
    return render_template('up_video.html',file_list=ret,all_file=len(FileName),pages=page,all_page=all_page)

@app.route('/next_page/<int:page>/', methods=['GET'])
def next_page(page):
    filepath = os.path.join(os.path.dirname(os.path.abspath('__file__')),'phone_win_file')
    if not os.path.exists(filepath):
        os.makedirs(filepath)
    FileName,FileNameWithPath,FileDir = GetNameByEveryDir(filepath)
    limit = 10
    all_page=int(len(FileName)/limit)+1
    pages = int(page)
    if pages<=0:
        pages=1
    elif pages>=all_page:
        pages=int(all_page)                                   
    else:
        pages=int(page)                            
    start = (pages - 1) * limit                
    end = pages * limit if len(FileName) > pages * limit else len(FileName)                             
    ret = [FileName[i] for i in range(start, end)]

    return render_template('up_video.html',file_list=ret,all_file=len(FileName),pages=pages,all_page=all_page)
    
@app.route('/phone_win_file/<file_name>', methods=['GET'])
def phone_win_file(file_name):
    try:
        filepath = os.path.join(os.path.dirname(os.path.abspath('__file__')),'phone_win_file')
        if not os.path.exists(filepath):
            os.makedirs(filepath)
        filename =file_name
        # print(file_name)
        file = os.path.join(filepath, filename)
        return send_file(file,conditional=True)
    except Exception as e:
        return json.dumps({'code': "502"}, ensure_ascii=False)

@app.route('/up_video', methods=['post'])
def up_video():
    try:
        filepath = os.path.join(os.path.dirname(os.path.abspath('__file__')),'phone_win_file')
        if not os.path.exists(filepath):
            os.makedirs(filepath)
        for f in request.files.getlist('file'):
            if f and '/' in f.filename:
                print('这是文件夹')
                temp_path=filepath+os.sep+f.filename.split('/')[0]
                if not os.path.exists(temp_path):
                    os.makedirs(temp_path)
                filename = f.filename.split('/')[1]
                upload_path = os.path.join(temp_path,filename)
                f.save(upload_path)
            elif f:
                print('这是多文件')
                filename = f.filename
                upload_path = os.path.join(filepath,filename)
                f.save(upload_path)
            else:
                continue
        return render_template('up_video_ok.html')
    except Exception as e:
        # print(e)
        return json.dumps({'code': "502"}, ensure_ascii=False)

#------------------------------------远程文件-----------------------------------------#
# -----------------------------------诗开始----------------------------------------#
def response_return(code, msg, data):
    """[summary]
    Args:
        code ([type]): 200(请求成功),404(请求失败),500(服务器出错)
        msg ([type]): msg
        data ([type]): json_data
    Returns:
        [type]: [description]
    """
    if data == None:
        data = []
    return json.dumps({'code': code, 'msg': msg, 'data': list(data)}, ensure_ascii=False)

def write_error(e):
    """[summary]
    Args:
        e ([type]): [description]
    """
    with open('error.txt', 'a') as file_handle:
        file_handle.write("error: %s--%s" %
                          (e.__traceback__.tb_lineno, str(e)))  # 写入
        file_handle.write('\n')
        
def seach(strs):
    poemList = []
    #--------------------------------唐诗------------------------------------------------#
    all_poem = []
    a = tang_poem_selectParagraphss(strs)
    if a != []:
        for i in a:
            all_poem.append(i)
#------------------------------------------宋诗----------------------------------------#
    b = song_poem_selectParagraphss(strs)
    if b != []:
        for i in b:
            all_poem.append(i)
#--------------------------------------宋词------------------------------------------#
    c = ci_poem_selectParagraphss(strs)
    if c != []:
        for i in c:
            all_poem.append(i)
#——------------------------------------------整理------------------------------#
    for i in all_poem:
        try:
            poemDict = {}
            poemDict['poemName'] = i[1]
            poemDict['author'] = i[2]
            poemDict['poem'] = i[4]
            poemList.append(poemDict)
        except:
            poemDict['poem'] = i[3]

# -----------------------------------用户原创----------------------------------------#
    d = use_poem_selectall(strs)
    if d != []:
        for i in d:
            poemDict = {}
            poemDict['poemName'] = i[1]
            poemDict['author'] = i[2]
            poemDict['poem'] = i[3]
            poemList.append(poemDict)
            
# -----------------------------------鸡/毒汤文----------------------------------------#
    if strs =='鸡汤':
        e = dutang_selectParagraphss('')
    else:
        e = dutang_selectParagraphss(strs)
    if e != []:
        for i in e:
            poemDict = {}
            poemDict['poemName'] = '鸡汤文'
            poemDict['author'] = '佚名'
            poemDict['poem'] = i[1]
            poemList.append(poemDict)
    
    if strs=='毒汤':
        f = dutang_selectParagraphss('')
    else:
        f = dutang_selectParagraphss(strs)
    if f != []:
        for i in f:
            poemDict = {}
            poemDict['poemName'] = '毒汤文'
            poemDict['author'] = '佚名'
            poemDict['poem'] = i[1]
            poemList.append(poemDict)
            
    b = OrderedDict()

    for item in poemList:
        b.setdefault(item['poem'],{**item,})
    b = list(b.values())
    return b

@poem.route('/getPoem', methods=['GET', 'POST'])
def getPoem():
    """
    查找诗集
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    page    |    false    |    string   |    页码    |
    |    pagesize    |    false    |    string   |    返回每页数量    |
    |    poemInfo    |    true    |    string   |    查找关键词    |

    #### return
    - ##### json
    > {
        "code": 200,
        "msg": "success",
        "data":[
        {'poemName': '咏风', 'author': '太宗皇帝', 'poem': '萧条起...'},
        {'poemName': '咏雨', 'author': '太宗皇帝', 'poem': '罩云飘...'}]}

    #### test
    ```
    # -*- coding: utf-8 -*-
    # @Time    : 2020/3/29 7:57
    # @Author  : Cxk
    # @File    : test.py
    import requests, json
    data = {
        'poemInfo': '李白',
        'page':'1',
        'pagesize':'2',
    }
    url = 'http://127.0.0.1:5000/poem/getPoem'
    r = requests.post(url, data=json.dumps(data))
    print(r.json())
    ```
    @@@
    """
    try:
        if not request.data:
            limit=10
            page=1
            strs='李白'
        else:
            post_data = request.data.decode('utf-8')
            # 获取到POST过来的数据，因为我这里传过来的数据需要转换一下编码。根据具体情况而定
            data_json = json.loads(post_data)
            limit = int(data_json['pagesize'])
            page = int(data_json['page'])
            strs = data_json['poemInfo']
            # 把获取到的数据转为JSON格式。
        if strs == 'all':
            strs = ''
        data = seach(str(strs))
        # print(len(data))
        start = (page - 1) * limit
        end = page * limit if len(data) > page * limit else len(data)
        # print(end)
        all_ret=[]
        ret = [data[i] for i in range(start, end)]
        # print(ret)
        all_ret.append(str(len(data)))
        all_ret.append(ret)
        return response_return('200', 'success', all_ret)
    except Exception as e:
        write_error(e)
        return response_return('404', 'Request parameter error', None)


@poem.route('/getAudioList', methods=['GET', 'POST'])
def getAudioList():
    """
    返回所有用户读诗语音,以及用户原创分享
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    page    |    false    |    string   |    页码    |
    |    pagesize    |    false    |    string   |    返回每页数量    |
    |    value    |    true    |    string   |    查找关键词    |

    #### return
    - ##### json
    > {"code": 200, "msg": "success","data":[[],[]]}
    
    - ##### 说明：data第一个列表为语音，第二个列表为用户原创
    @@@
    """
    try:
        if not request.data:
            limit=10
            page=1
            value=''
        else:
            post_data = request.data.decode('utf-8')
            # 获取到POST过来的数据，因为我这里传过来的数据需要转换一下编码。根据具体情况而定
            data_json = json.loads(post_data)
            limit = int(data_json['pagesize'])
            page = int(data_json['page'])
            value = data_json['value']
        if value == '':
            audioArr = []
            data = use_audio_select()
            for i in data[::-1]:
                a = {'imgurl': "", 'username': '', 'poemname': '', 'author': '', 'poem': "", 'src': '',
                     'bl': '0', 'count_like': 0, "see": 0, 'like': '0'}
                b = use_selectOpenid(i[0])
                a['username'] = str(b[0][1])
                a['imgurl'] = str(b[0][2])
                a['poemname'] = str(i[2])
                a['author'] = str(i[3])
                a['poem'] = str(i[4])
                a['src'] = str(i[1])
                audioArr.append(a)
            # print(audioArr)
            usepoemArr = []
            data2 = use_poem_select()
            for i in data2[::-1]:
                a = {'imgurl': "", 'username': '', 'title': '',
                     'author': '', 'poem': "", 'imgurls': '', }
                b = use_selectOpenid(i[0])
                a['username'] = str(b[0][1])
                a['imgurl'] = str(b[0][2])
                a['title'] = str(i[1])
                a['author'] = str(i[2])
                a['poem'] = str(i[3])
                a['imgurls'] = str(i[4])
                usepoemArr.append(a)

            start = (page - 1) * limit
            end = page * limit if len(audioArr) > page * \
                limit else len(audioArr)

            ret = [audioArr[i] for i in range(start, end)]

            start = (page - 1) * limit
            end = page * limit if len(usepoemArr) > page * \
                limit else len(usepoemArr)

            rets = [usepoemArr[i] for i in range(start, end)]
            all_ret=[]
            all_ret.append(ret)
            all_ret.append(rets)
            return response_return('200', 'success', all_ret)
        else:
            audioArr = []
            data = use_audio_selectall(value)
            for i in data[::-1]:
                a = {'imgurl': "", 'username': '', 'poemname': '', 'author': '', 'poem': "", 'src': '',
                     'bl': '0', 'count_like': 0, "see": 0, 'like': '0'}
                b = use_selectOpenid(i[0])
                a['username'] = str(b[0][1])
                a['imgurl'] = str(b[0][2])
                a['poemname'] = str(i[2])
                a['author'] = str(i[3])
                a['poem'] = str(i[4])
                a['src'] = str(i[1])
                audioArr.append(a)
            # print(audioArr)
            usepoemArr = []
            data2 = use_poem_selectall(value)
            for i in data2[::-1]:
                a = {'imgurl': "", 'username': '', 'title': '',
                     'author': '', 'poem': "", 'imgurls': '', }
                b = use_selectOpenid(i[0])
                a['username'] = str(b[0][1])
                a['imgurl'] = str(b[0][2])
                a['title'] = str(i[1])
                a['author'] = str(i[2])
                a['poem'] = str(i[3])
                a['imgurls'] = str(i[4])
                usepoemArr.append(a)
            start = (page - 1) * limit
            end = page * limit if len(audioArr) > page * \
                limit else len(audioArr)
            ret = [audioArr[i] for i in range(start, end)]

            start = (page - 1) * limit
            end = page * limit if len(usepoemArr) > page * \
                limit else len(usepoemArr)
            rets = [usepoemArr[i] for i in range(start, end)]
            
            all_ret=[]
            all_ret.append(ret)
            all_ret.append(rets)
            return response_return('200', 'success', all_ret)
    except Exception as e:
        write_error(e)
        return response_return('404', 'Request parameter error', None)

@poem.route('/alter_info', methods=['GET', 'POST'])
def alter_info():
    """
    修改用户信息
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    openid    |    false    |    string   |    用户微信ID    |
    |    nickname    |    false    |    string   |    昵称    |
    |    sign    |    false    |    string   |    个性签名    |

    #### return
    - ##### json
    > {code": 200,"msg": "success","data":["",[]]}
    - ##### 说明：data第一个字符串为用户id，第二个列表为用户信息
    @@@
    """
    try:
        if not request.data:
            return response_return('404', 'Request parameter error', None)    
        post_data = request.data.decode('utf-8')
        # 获取到POST过来的数据，因为我这里传过来的数据需要转换一下编码。根据具体情况而定
        data_json = json.loads(post_data)
        openid = data_json['openid']
        nickname = data_json['nickname']
        sign = data_json['sign']
        use_alterOpenid(nickname, sign, openid)
        a = use_selectOpenid(openid)
        userInfo = {}
        userInfo['nickname'] = a[0][1]
        userInfo['avatarUrl'] = a[0][2]
        userInfo['gender'] = a[0][3]
        userInfo['sign'] = a[0][4]
        ret=[]
        ret.append(openid)
        ret.append(userInfo)
        return response_return('200', 'success', ret)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)


@poem.route('/getUsePoem', methods=['GET', 'POST'])
def getUsePoem():
    """
    获取某个用户数据
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    openid    |    false    |    string   |    用户微信ID    |

    #### return
    - ##### json
    > {"code": 200, "msg": "success","data":[[],[]]}
    
    - ##### 说明：data第一个列表为语音，第二个列表为用户原创
    @@@
    """
    try:
        if not request.data:
            return response_return('404', 'Request parameter error', None)
        post_data = request.data.decode('utf-8')
        # 获取到POST过来的数据，因为我这里传过来的数据需要转换一下编码。根据具体情况而定
        data_json = json.loads(post_data)
        openid = data_json['openid']
        a = use_poem_selectOpenid(openid)
        c = use_audio_selectOpenid(openid)
        use_poem = []
        use_audio = []
        for i in a[::-1]:
            b = {'title': '', 'author': '', 'poem': "", 'imgurls': ''}
            b['title'] = str(i[1])
            b['author'] = str(i[2])
            b['poem'] = str(i[3])
            b['imgurls'] = str(i[4])
            use_poem.append(b)
        for i in c[::-1]:
            d = {'poemname': '', 'author': '',
                    'poem': "", 'src': '', 'bl': '0'}
            d['poemname'] = str(i[2])
            d['author'] = str(i[3])
            d['poem'] = str(i[4])
            d['src'] = str(i[1])
            use_audio.append(d)
            
        all_ret=[]
        all_ret.append(use_audio)
        all_ret.append(use_poem)
        return response_return('200', 'success', all_ret)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)

@poem.route('/get_question', methods=['GET', 'POST'])
def get_question():
    """
    获得某个用户反馈
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    openid    |    false    |    string   |    用户微信ID    |
    |    question    |    false    |    string   |    问题类型    |
    |    allquestion    |    false    |    string   |    问题描述    |
    
    #### return
    - ##### json
    > {"code": 200, "msg": "success","data":[]}
    @@@
    """
    try:
        if not request.data:
            return response_return('404', 'Request parameter error', None)
        post_data = request.data.decode('utf-8')
        # 获取到POST过来的数据，因为我这里传过来的数据需要转换一下编码。根据具体情况而定
        data_json = json.loads(post_data)
        openid = data_json['openid']
        question = data_json['question']
        allquestion = data_json['allquestion']
        content = "用户id:"+openid+"\n问题类型：\n"+question+"\n问题描述：\n"+allquestion
        send_qqemails(content)
        return response_return('200', 'success', None)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)

@poem.route('/get_id', methods=['GET', 'POST'])
def get_id():
    """
    获得某个用户ID
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    code    |    false    |    string   |    用户微信登录码    |
    |    headurl    |    false    |    string   |    头像地址    |
    |    nickname    |    false    |    string   |    昵称    |
    |    gender    |    false    |    string   |    性别    |
    
    #### return
    - ##### json
    > {"code": 200, "msg": "success","data":["用户id",[用户信息列表]]}
    
    - ##### 说明：data第一个字符串为用户id，第二个列表为用户信息
    @@@
    """
    try:
        if not request.data:
            return response_return('404', 'Request parameter error', None)
        post_data = request.data.decode('utf-8')
        # 获取到POST过来的数据，因为我这里传过来的数据需要转换一下编码。根据具体情况而定
        data_json = json.loads(post_data)

        code = data_json['code']
        headurl = str(data_json['headurl'])
        nickname = data_json['nickname']
        # 性别0：未知、1：男、2：女
        gender = str(data_json['gender'])
        sign = '真正适合你的人像一杯温暖的热茶，暖心又暖胃。'
        # print("用户的临时code：%s\n头像地址：%s\n昵称：%s\n" % (code, headurl, nickname))
        APPID = "wx569aa32199783620"
        SECRET = "a931e3a977ca3da1b33c927834978537"
        url = 'https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code'.format(
            appid=APPID, secret=SECRET, code=code)
        res = requests.get(url)
        openid = res.json().get('openid')
        # session_key = res.json().get('session_key')
        # 删除用户 慎用
        # use_delOpenid(openid)
        a = use_selectOpenid(openid)
        if a == []:
            use_insertData(openid, nickname, headurl, gender, sign)
            a = use_selectOpenid(openid)
            userInfo = {}
            userInfo['nickname'] = a[0][1]
            userInfo['avatarUrl'] = a[0][2]
            userInfo['gender'] = a[0][3]
            userInfo['sign'] = a[0][4]
            
            all_ret=[]
            all_ret.append(openid)
            all_ret.append(userInfo)
            print(all_ret)
            return response_return('200', 'success', all_ret)
        else:
            a = use_selectOpenid(openid)
            userInfo = {}
            userInfo['nickname'] = a[0][1]
            userInfo['avatarUrl'] = a[0][2]
            userInfo['gender'] = a[0][3]
            userInfo['sign'] = a[0][4]

            all_ret=[]
            all_ret.append(openid)
            all_ret.append(userInfo)
            print(all_ret)
            return response_return('200', 'success', all_ret)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)


@poem.route('/find_audio', methods=['GET', 'POST'])
def find_audio():
    """
    机器生成诗句语音上传保存
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    poemName    |    false    |    string   |    诗名    |
    |    author    |    false    |    string   |    作者    |
    |    poem    |    false    |    string   |    诗句    |
    
    #### return
    - ##### json
    > {"code": 200, "msg": "success","data":[]]}
    @@@
    """
    try:
        fileinfo = request.data.decode('utf-8')
        data_json = json.loads(fileinfo)
        filepath = os.path.join(os.path.dirname(
            os.path.abspath(__file__)), 'audio')
        poemName = data_json['poemName']
        author = data_json['author']
        poem = data_json['poem']
        file = poemName+"_"+author+".mp3"
        file = os.path.join(filepath, file)
        if os.path.exists(file):
            return response_return('404', 'file already exist', None)
        else:
            name = poemName+"_"+author
            text = poemName+","+author+","+poem
            getBaiduVoice(text, name)
            return response_return('200', 'success', None)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)

# 获取并保存文件
@poem.route('/audiofile', methods=['GET', 'POST'])
def audiofile():
    """
    录制的语音上传保存
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    file    |    false    |    string   |    文件描述符    |
    |    openid    |    false    |    string   |    用户微信ID    |
    |    poemName    |    false    |    string   |    诗名    |
    |    author    |    false    |    string   |    作者    |
    |    poem    |    false    |    string   |    诗句    |
    
    #### return
    - ##### json
    > {"code": 200, "msg": "success","data":[]]}
    @@@
    """
    try:
        file = request.files['file']
        openid = request.values.get('openid')
        poemname = request.values.get('poemname')
        author = request.values.get('author')
        poem = request.values.get('poem')
        print("id：%s,诗名：%s，作者：%s，诗句：%s" % (openid, poemname, author, poem))
        sm = '1'  # 公开
        filename = str(openid) + '_' + str(poemname) + '_' + \
            str(author)+"_"+str(poem)[0:5] + ".mp3"
        audioname = 'http://www.cxkboke.top/useraudio/'+filename
        use_audio_insertData(openid, audioname, poemname, author, poem, sm)
        print('语音数据保存成功！')
        BASE_DIR = os.path.dirname(__file__)  # 获得当前父目录
        save_path = os.path.join(
            BASE_DIR, "useraudio", filename)  # 在父目录的useraudio文件下保存
        print(save_path)
        file.save(save_path)
        return response_return('200', 'success', None)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)


@poem.route('/audio/<file_names>', methods=['GET'])
def audio(file_names):
    """
    机器合成音频传输播放
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    file_names    |    false    |    string   |    音频文件名    |
    
    #### return
    - ##### file
    > 文件输出
    @@@
    """
    try:
        filepath = os.path.join(os.path.dirname(
            os.path.abspath(__file__)), 'audio')
        filename = file_names
        file = os.path.join(filepath, filename)
        return send_file(file)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)


@poem.route('/useraudio/<file_name>', methods=['GET', 'POST'])
def useraudio(file_name):
    """
    用户录制音频传输播放
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    file_name    |    false    |    string   |    音频文件名    |
    
    #### return
    - ##### file
    > 文件输出
    @@@
    """
    try:
        filepath = os.path.join(os.path.dirname(
            os.path.abspath(__file__)), 'useraudio')
        print(filepath)
        filename = file_name
        file = os.path.join(filepath, filename)
        print(file)
        return send_file(file)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)

@poem.route('/up_photo', methods=['post'])
def up_photo():
    """
    用户原创分享，带图片
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    file    |    false    |    string   |    图片文件描述符    |
    |    openid    |    false    |    string   |    用户微信ID    |
    |    title    |    false    |    string   |    标题    |
    |    author    |    false    |    string   |    作者    |
    |    poem    |    false    |    string   |    诗句    |
    
    #### return
    - ##### json
    > {"code": 200, "msg": "success","data":[]]}
    @@@
    """
    try:
        file = request.files['file']
        openid = request.values.get('openid')
        title = request.values.get('title')
        author = request.values.get('author')
        poem = request.values.get('poem')
        print(openid, title, author, poem)
        nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # 生成当前时间
        randomNum = random.randint(0, 100)  # 生成的随机整数n，其中0<=n<=100
        if randomNum <= 10:
            randomNum = str(0) + str(randomNum)
        uniqueNum = str(nowTime) + str(randomNum)
        filename = uniqueNum + '.jpg'
        BASE_DIR = os.path.dirname(__file__)
        save_path = os.path.join(BASE_DIR, "static/img", filename)
        file.save(save_path)
        print(save_path)
        imgurl = "https://www.cxkboke.top/static/img/"+filename
        use_poem_insertData(openid, title, author, poem, imgurl)
        print('插入成功！')
        return response_return('200', 'success', None)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)


@poem.route('/up_photo_2', methods=['post'])
def up_photo_2():
    """
    用户原创分享，不带图片
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    openid    |    false    |    string   |    用户微信ID    |
    |    title    |    false    |    string   |    标题    |
    |    author    |    false    |    string   |    作者    |
    |    poem    |    false    |    string   |    诗句    |
    
    #### return
    - ##### json
    > {"code": 200, "msg": "success","data":[]]}
    @@@
    """
    try:
        post_data = request.data.decode('utf-8')
        # 获取到POST过来的数据，因为我这里传过来的数据需要转换一下编码。根据具体情况而定
        data_json = json.loads(post_data)
        openid = data_json['openid']
        title = data_json['title']
        author = data_json['author']
        poem = data_json['poem']
        imgurl = 'None'
        use_poem_insertData(openid, title, author, poem, imgurl)
        print('插入成功！')
        return response_return('200', 'success', None)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)

@poem.route('/up_photo_3', methods=['post'])
def up_photo_3():
    """
    图片文字识别接口
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    file    |    false    |    string   |    图片文件描述符    |
    
    #### return
    - ##### json
    > {"code": 200, "msg": "success","data":[{"words":"窗前明月光"}]}
    @@@
    """
    try:
        file = request.files['file']
        nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # 生成当前时间
        randomNum = random.randint(0, 100)  # 生成的随机整数n，其中0<=n<=100
        if randomNum <= 10:
            randomNum = str(0) + str(randomNum)
        uniqueNum = str(nowTime) + str(randomNum)
        filename = uniqueNum + '.jpg'
        BASE_DIR = os.path.dirname(__file__)
        save_path = os.path.join(BASE_DIR, "static/test_poem", filename)
        file.save(save_path)
        all_ret=[]
        all_key_word=img_word(save_path)
        if all_key_word:
            all_ret.append(all_key_word)
        os.remove(save_path)
        return response_return('200', 'success',all_ret)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)
        
@poem.route('/del_audio_poem', methods=['GET', 'POST'])
def del_audio_poem():
    """
    用户语音删除
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    flag    |    false    |     int(1/0)   |    语音还是原创标志    |
    |    audioname    |    false    |    string   |    语音名    |
    |    poem    |    false    |    string   |    原创名    |
    
    #### return
    - ##### json
    > {"code": 200, "msg": "success","data":[]]}
    
    - ##### 说明：audioname与poem参数二选一
    @@@
    """
    try:
        if not request.data:
            return response_return('404', 'Request parameter error', None)    
        post_data = request.data.decode('utf-8')
        # 获取到POST过来的数据，因为我这里传过来的数据需要转换一下编码。根据具体情况而定
        data_json = json.loads(post_data)
        flag = data_json['flag']
        if flag == 1:
            audioname = data_json['audioname']
            use_audio_delaudioname(audioname)
            return response_return('200', 'success', None)
        else:
            poem = data_json['poem']
            use_poem_delpoem(poem)
            return response_return('200', 'success', None)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)



@poem.route('/del_all', methods=['GET', 'POST'])
def del_all():
    """
    用户注销
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    openid    |    false    |    string   |    用户微信ID    |

    
    #### return
    - ##### json
    > {"code": 200, "msg": "success","data":[]]}
    
    - ##### 说明：audioname与poem参数二选一
    @@@
    """
    try:
        if not request.data:
            return response_return('404', 'Request parameter error', None)  
        post_data = request.data.decode('utf-8')
        # 获取到POST过来的数据，因为我这里传过来的数据需要转换一下编码。根据具体情况而定
        data_json = json.loads(post_data)
        openid = data_json['openid']
        use_delOpenid(openid)
        return response_return('200', 'success', None)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)

# -----------------------------------诗结束----------------------------------------#

#@app.route('/login', methods=['GET', 'POST'])
#def login():
#    return render_template('login.html')

@app.route('/logins', methods=['GET', 'POST'])
def logins():
    try:
        # 获取post数据
        username = request.form.get('username')
        phonenumber = request.form.get('phonenumber')
        money = request.form.get('money')
        if username=='' or phonenumber=='' or money=='':
            return render_template('fail.html')
        else:
            print(username, phonenumber, money)
            wai_InsertData(username, phonenumber, money)
            print("数据库添加成功")
            content = "用户姓名：" + str(username) + "\n用户电话号码：" + str(phonenumber) + "\n￥大小：\n" + str(money)
            send_qqemails(content)
            return render_template('successs.html')
    except:
        return render_template('login.html')

        
# 判断网站来自mobile还是pc
def checkMobile(request):
    """
    demo :
        @app.route('/m')
        def is_from_mobile():
            if checkMobile(request):
                return 'mobile'
            else:
                return 'pc'
    :param request:
    :return:
    """
    userAgent = request.headers['User-Agent']

    _long_matches = r'googlebot-mobile|android|avantgo|blackberry|blazer|elaine|hiptop|ip(hone|od)|kindle|midp|mmp|mobile|o2|opera mini|palm( os)?|pda|plucker|pocket|psp|smartphone|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce; (iemobile|ppc)|xiino|maemo|fennec'
    _long_matches = re.compile(_long_matches, re.IGNORECASE)
    _short_matches = r'1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-'
    _short_matches = re.compile(_short_matches, re.IGNORECASE)

    if _long_matches.search(userAgent) != None:
        return True
    user_agent = userAgent[0:4]
    if _short_matches.search(user_agent) != None:
        return True
    return False


@app.route('/jianli2', methods=['GET', 'POST'])
def jianli2():
    if checkMobile(request):
        return render_template('jianli3.html')
    else:
        return render_template('jianli2.html')



@app.route('/jianli', methods=['GET', 'POST'])
def jianli():
    return render_template('jianli.html')

@app.route('/contact_me', methods=['GET', 'POST'])
def contact_me():
    # 获取post数据
    name = request.form.get('name')
    email = request.form.get('email')
    liuyan = request.form.get('liuyan')
    times = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    print(name, email, liuyan)
    user_InsertData(name, email, liuyan, times)
    content = "留言姓名：" + str(name) + "\n留言人邮箱地址：" + str(email) + "\n留言内容：\n" + str(liuyan)
    send_qqemail(content)
    return render_template('success.html')
#--------------------------------------------------美团美食----------------------#
def chiose(pf,pl,xf):
    """
    (4,1000,100)
    评分大于 4，评论数大于 1000，消费小于 100
    :param pf: 店铺评分
    :param pl: 店铺评论数
    :param xf: 平均消费
    :return: 符合要求的店铺列表嵌套字典
    """
    allinfo = meituan_showAll()
    first = []
    for i in allinfo:
        info_dict = {}
        if float(i[4]) >= pf and float(i[6]) >= pl and float(i[7]) <= xf:
            info_dict['商家名字'] = i[3]
            info_dict['商家地址'] = i[5]
            info_dict['商家评分'] = i[4]
            info_dict['商家评论数'] = i[6]
            info_dict['平均个人消费'] = i[7]
            info_dict['lng'] = i[8]
            info_dict['lat'] = i[9]
            first.append(info_dict)
    # print(len(first))
    return first


def getlnglat(pf,pl,xf):
    data_info = []
    for i in chiose(pf,pl,xf):
        strs = "%s<br/>%s<br/>评分：%s<br/>评论数：%s<br/>平均消费：%s￥" % (
        i['商家名字'], i['商家地址'][0:25], i['商家评分'], i['商家评论数'], i['平均个人消费'])
        a = []
        a.append(i['lng'])
        a.append(i['lat'])
        a.append(strs)
        data_info.append(a)
    return data_info


# 首页
@app.route('/meituan_meishi')
def meituan_meishi():
    pf=4
    pl=1000
    xf=50
    data_new_map = getlnglat(pf,pl,xf)
    return render_template('baidu_map.html', data_new_map=json.dumps(data_new_map))

@app.route("/saixuan",methods=['POST']) #请求方式为post
def saixuan():
    try:
        pf = float(request.form['pf'])
        pl = float(request.form['pl'])
        xf = float(request.form['xf'])
        data_new_map = getlnglat(pf, pl, xf)
        return render_template('baidu_map.html', data_new_map=json.dumps(data_new_map))
    except:
        data_new_map = getlnglat(4, 1000, 50)
        return render_template('baidu_map.html', data_new_map=json.dumps(data_new_map))

@app.route('/getJitang', methods=['GET', 'POST'])
def getJitang():
    try:
        if request.method == 'POST':
            if not request.data:
                # 检测是否有数据
                return json.dumps({'msg': "错误，没有请求参数！", 'info': [{'poemName': '无', 'author': '无', 'poem': '无'}]},ensure_ascii=False)
            post_data = request.data.decode('utf-8')
            # 获取到POST过来的数据，因为我这里传过来的数据需要转换一下编码。根据具体情况而定
            data_json = json.loads(post_data)
            chiose = data_json['chiose']
            if chiose=='ji':
                print(jitang_select()[0][1])
                return json.dumps({'code':'200' , 'info': jitang_select()[0][1]}, ensure_ascii=False)
            elif chiose == 'du':
                print(dutang_select()[0][1])
                return json.dumps({'code': '200', 'info': dutang_select()[0][1]}, ensure_ascii=False)
        else:
            return json.dumps({'msg': "请求失败，请用post提交", 'info': 'None'},
                              ensure_ascii=False)
    except Exception as e:
        with open('error.txt', 'a') as file_handle:
            file_handle.write("函数: " + str(e))  # 写入
            file_handle.write('\n')

@app.route('/getYingyu', methods=['GET', 'POST'])
def getYingyu():
    try:
        if request.method == 'POST':
            Y = '2020'
            m = random.randint(1, 12)
            if m < 10:
                M = '0' + str(m)
            else:
                M = str(m)
            d = random.randint(1, 28)
            if d < 10:
                D = '0' + str(d)
            else:
                D = str(d)
            url = 'http://sentence.iciba.com/index.php?c=dailysentence&m=getdetail&title=' + Y + "-" + M + "-" + D
            r = requests.post(url)
            a = r.json()
            try:
                return json.dumps({'msg': '200', 'info': a['content'] + '\n' + a['note']}, ensure_ascii=False)
            except:
                return json.dumps({'msg': '200', 'info': '这碗洒了，再来一碗！'}, ensure_ascii=False)
        else:
            return json.dumps({'msg': "请求失败，请用post提交", 'info': '这碗洒了，再来一碗！'},
                              ensure_ascii=False)
    except Exception as e:
        with open('error.txt', 'a') as file_handle:
            file_handle.write("函数: " + str(e))  # 写入
            file_handle.write('\n')
            
#------------------------------------diancan-----------------------------------------#
##################################################################################################################
from dian_can_info_sql import *
# 首页
@app.route('/dian_can_index')
def dian_can_index():
    data=user_slectTable()[::-1]
    all_data=[]
    zao_sum=0
    wu_sum=0
    wan_sum=0
    for i in data:
        temp={}
        temp['id']=i[0]
        temp['name']=i[1]
        temp['nian_ji']=i[2]
        temp['zao_number']=i[3]
        temp['wu_number']=i[4]
        temp['wan_number']=i[5]
        temp['eat_day']=i[6]
        temp['eat_week']=i[7]
        temp['dian_can_time']=i[8]
        zao_sum+=i[3]
        wu_sum+=i[4]
        wan_sum+=i[5]
        all_data.append(temp)
        
    return render_template('dian_can_index.html',all_data=all_data,zao_sum=zao_sum,wu_sum=wu_sum,wan_sum=wan_sum)

@app.route('/search_data',methods=['GET', 'POST'])
def search_data():
    name_key = request.form.get('name_key')
    nian_ji_key = request.form.get('nian_ji_key')
    month_key = request.form.get('month_key')
    data=user_slectTable()[::-1]
    all_data=[]
    zao_sum=0
    wu_sum=0
    wan_sum=0
    for i in data:
        temp={}
        if name_key in i[1] and nian_ji_key in i[2] and month_key in i[6]:
            temp['id']=i[0]
            temp['name']=i[1]
            temp['nian_ji']=i[2]
            temp['zao_number']=i[3]
            temp['wu_number']=i[4]
            temp['wan_number']=i[5]
            temp['eat_day']=i[6]
            temp['eat_week']=i[7]
            temp['dian_can_time']=i[8]
            zao_sum+=i[3]
            wu_sum+=i[4]
            wan_sum+=i[5]
            all_data.append(temp)
    return render_template('dian_can_index.html',all_data=all_data,zao_sum=zao_sum,wu_sum=wu_sum,wan_sum=wan_sum)

@app.route('/data_api',methods=['GET', 'POST'])
def data_api():
    try:
        data=user_slectTable()[::-1]
        all_data=[]
        for i in data:
            temp={}
            temp['id']=i[0]
            temp['name']=i[1]
            temp['nian_ji']=i[2]
            temp['zao_number']=i[3]
            temp['wu_number']=i[4]
            temp['wan_number']=i[5]
            temp['eat_day']=i[6]
            temp['eat_week']=i[7]
            temp['dian_can_time']=i[8]
            all_data.append(temp)
        return response_return('200', 'success', all_data)
    except:
        all_data=[]
        return response_return('404', 'fail', all_data)


@app.route('/input_data',methods=['GET', 'POST'])
def input_data():
    try:
        title="点餐信息上传成功！"
        time_stamp = datetime.datetime.now()
        time=str(time_stamp.strftime('%H:%M:%S')).split(':')[0]
        if int(time)>=23 or int(time) <=6:
            return render_template('up_data_ok.html',title="已超过点餐时间！")
        name = request.form.get('name')
        select_nian_ji = request.form.get('select_nian_ji')
        zao_numbers = request.form.get('zao_numbers')
        wu_numbers = request.form.get('wu_numbers')
        wan_numbers = request.form.get('wan_numbers')
        nian_ji_dict={"qi":"七年级","ba":"八年级","jiu":"九年级","shi":"高一","shi_yi":"高二","shi_er":"高三"}
        if name == '':
            title="姓名不能为空！"
            return render_template('up_data_ok.html',title=title)
        if zao_numbers == '' or int(zao_numbers) < 0:
            zao_numbers=0
        if wu_numbers == '' or int(wu_numbers) < 0 :
            wu_numbers=0
        if wan_numbers == '' or int(wan_numbers) < 0:
            wan_numbers=0
        # if int(zao_numbers)+int(wu_numbers)+int(wan_numbers)==0:
        #     title="您未点餐！"
        #     return render_template('up_data_ok.html',title=title)
        today = datetime.date.today()
        tomorrow = today + datetime.timedelta(days=1)
        week=tomorrow.isoweekday()
        weekday={1:"星期一",2:"星期二",3:"星期三",4:"星期四",5:"星期五",6:"星期六",7:"星期日"}
        today_week = today.isoweekday()
        time_stamp = datetime.datetime.now()
        time=str(time_stamp.strftime('%Y.%m.%d-%H:%M:%S'))+"-"+weekday[today_week]
        res=user_slect_name_day(str(name),tomorrow)
        if res != []:
            title="点餐信息已覆盖！"
            user_alter(res[0][0],int(zao_numbers),int(wu_numbers),int(wan_numbers),time)
            return render_template('up_data_ok.html',title=title)
        else:
            user_insertData(str(name),nian_ji_dict[select_nian_ji],int(zao_numbers),int(wu_numbers),int(wan_numbers),tomorrow,weekday[week],time)
            return render_template('up_data_ok.html',title=title)
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)
        title="未知错误，请重新点餐！"
        return render_template('up_data_ok.html',title=title)



##################################################################################################################
app.register_blueprint(poem, url_prefix='/poem')

if __name__ == '__main__':
    app.run(debug=True)
#ssl_context=('cert/3638398_www.cxkboke.top.pem', 'cert/3638398_www.cxkboke.top.key'))
